<template>
  <div class="app-container">
    <div class="filter-container">
      <k-button v-if="authorityHandle(174)" class="top-btn" value="添加头像框" @click.native="addAvatarDialog" />
      <k-input
        v-model.trim="keyword"
        class="filter-item"
        is-search
        placeholder="头像框名称、备注"
        :search-fun="handleFilter"
        @keyup.enter.native="handleFilter"
      />
    </div>
    <!--表格相关 -->
    <el-table
      ref="dragTable"
      :data="avatarList"
      fit
      border
      row-key="id"
      highlight-current-row
      style="width: 100%;border-radius:8px;"
      :header-cell-style="{background:'#F6F5FA',color:'#4E4F62'}"
    >
      <el-table-column type="index" label="序号" width="60px" align="center" />
      <el-table-column min-width="150px" label="图标" align="center">
        <template slot-scope="scope">
          <el-image style="width: 110px; height: 80px" :src="scope.row.iconUrl" :preview-src-list="[scope.row.iconUrl]" fit="contain" />
        </template>
      </el-table-column>
      <el-table-column prop="iconName" min-width="100px" label="名称" align="center" show-overflow-tooltip />
      <el-table-column prop="useTime" min-width="80px" label="使用期限" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.useTime === -1 ?'永久使用':'' }}
        </template>
      </el-table-column>
      <el-table-column prop="receiveName" min-width="100px" label="领取条件" align="center" show-overflow-tooltip />
      <el-table-column min-width="100px" label="领取时间" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.receiveStartTime }}-{{ scope.row.receiveEndTime }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" min-width="100px" label="备注说明" align="center" show-overflow-tooltip />
      <el-table-column min-width="200px" label="开关" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.iconStatus"
            :disabled="!authorityHandle(174)"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            active-text="开"
            inactive-text="关"
            :active-value="1"
            :inactive-value="2"
            @change="avatarOnlineState($event,scope)"
          />
        </template>
      </el-table-column>
      <el-table-column v-if="authorityHandle(174)" min-width="200px" label="操作" align="center">
        <template slot-scope="scope">
          <div class="op-div">
            <k-button class="table-btn" value="修改" @click.native="avatarUpdateDialog(scope.row)" />
            <!-- :disabled="scope.row.boxStatus === 1 ? true : false" -->
            <k-button class="table-btn" value="删除" @click.native="deleteAvatar(scope.row.id)" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加箱子 弹窗 -->
    <k-dialog
      :show-hide.sync="addBox.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      :title="textMap[dialogStatus]"
      class="addBox-dialog"
      :show-foot="false"
      :two-btn="true"
      @click="saveIconDataClick"
    >
      <el-form :model="addAvatarInfo" label-width="auto" class="form-modify">
        <el-form-item label="名称：">
          <el-input v-model="addAvatarInfo.iconName" show-word-limit placeholder="请输入头像名称" />
        </el-form-item>
        <el-form-item label="图标：" prop="iconUrl">
          <k-upload-file
            ref="upload1"
            v-model="addAvatarInfo.iconUrl"
            upload-style="img"
            @successUpload="successUpload($event,0)"
          />
          <span style="color: #b2b2b2">只能上传jpg/png文件,且不超过2M</span>
        </el-form-item>
        <el-form-item label="使用期限：">
          <el-select v-model="addAvatarInfo.useTime" placeholder="请选择期限">
            <el-option
              v-for="item in useTimeOptions"
              :key="item.lineId"
              :label="item.lineName"
              :value="item.lineId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="领取条件：">
          <div class="chargeform">
            <el-select
              v-model="addAvatarInfo.receiveType"
              placeholder="请选择类型"
              style="width:120px;margin-right:10px"
              @change="receiveTypeChange"
            >
              <el-option label="免费" :value="1" />
              <el-option label="期间消费" :value="2" />
              <el-option label="累计消费" :value="3" />
            </el-select>
            <el-input
              v-show="addAvatarInfo.receiveType != 1"
              v-model="addAvatarInfo.receiveAmount"
              onkeyup="value=value.replace(/[^0-9.]/g,'')"
              placeholder="请输入数值"
              style="width:140px;"
            />
          </div>
        </el-form-item>
        <el-form-item v-show="addAvatarInfo.receiveType != 1" label="领取时间：">
          <!-- 					<el-date-picker v-model="timeCotinue" type="datetimerange" format="yyyy-MM-dd HH:mm:ss"
						value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期"
						end-placeholder="结束日期" @change="datetimerange" /> -->

          <el-date-picker
            v-show="addAvatarInfo.receiveType != 1"
            v-model="timeCotinue"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="datetimerange"
          />
        </el-form-item>
        <el-form-item label="备注说明：">
          <el-input v-model="addAvatarInfo.remark" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
    </k-dialog>
  </div>
</template>

<script>
import {
  saveIconData,
  updateIconData,
  listIconData,
  deleteIconData,
  updateIconStatus,
  updateIconSort
} from '@/api/avatar'
import Sortable from 'sortablejs'
export default {
  data() {
    return {
      ruleGuideContent: {
        content: ''
      },
      dialogStatus: 'create',
      textMap: {
        update: '修改',
        create: '创建'
      },
      ruleGuide: {
        showHide: false
      },
      timeValue: '',
      timeCotinue: '',
      useTimeOptions: [{
        lineName: '永久使用',
        lineId: -1
      }],
      addAvatarInfo: {
        id: '',
        iconName: '',
        iconUrl: '',
        useTime: '',
        receiveType: '',
        receiveAmount: '',
        remark: '',
        receiveStartTime: '',
        receiveEndTime: ''
      },
      addBox: {
        showHide: false
      },
      gradeSettingModel: {
        gradeList: [{
          id: undefined,
          grade: undefined,
          minRecharge: '',
          maxRecharge: ''
        }],
        decayPrice: ''
      },
      gradeSetting: {
        showHide: false
      },
      avatarList: [],
      avatarTempList: [],
      sortable: null,
      showAmount: true,
      keyword: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    receiveTypeChange(v) {
      if (v == 1) {
        this.addAvatarInfo.receiveAmount = 0
        this.timeCotinue = ''
        this.addAvatarInfo.receiveStartTime = ''
        this.addAvatarInfo.receiveEndTime = ''
      }
      // this.showAmount = v !== 1
    },
    // 搜索查询事件
    handleFilter() {
      if (this.keyword === null || this.keyword.trim().length <= 0) {
        this.avatarList = this.avatarTempList
        return
      }
      const list = this.avatarList.filter(item =>

        item.iconName && item.iconName.indexOf(this.keyword) !== -1 || item.remark && item.remark.indexOf(
          this.keyword) !== -1
      )

      if (list.length <= 0) {
        this.avatarList = this.avatarTempList
        return
      }
      this.avatarList = []
      this.avatarList.push(...list)
    },
    datetimerange(timeValue) {
      this.addAvatarInfo.receiveStartTime = this.timeCotinue ? timeValue[0] : null
      this.addAvatarInfo.receiveEndTime = this.timeCotinue ? timeValue[1] : null
    },
    // 等级箱子列表页加载数据
    getList() {
      listIconData().then(res => {
        this.avatarList = res.data
        Object.assign(this.avatarTempList, this.avatarList)
        this.$nextTick(() => {
          if (this.authorityHandle(174)) {
            this.setSort()
          }
        })
      })
    },
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.avatarList.splice(evt.oldIndex, 1)[0]
          this.avatarList.splice(evt.newIndex, 0, targetRow)
          this.avatarList = this.avatarList.reverse()
          this.avatarList.map((item, index) => {
            item.iconSort = index
          })
          updateIconSort(this.avatarList).then(res => {
            this.$log(res)
            this.getList()
          })
        }
      })
    },
    addAvatarDialog() {
      this.addBox.showHide = true
      this.dialogStatus = 'create'
      this.timeCotinue = ''
      this.$resetForm(this.addAvatarInfo)
    },
    avatarUpdateDialog(row) {
      this.dialogStatus = 'update'
      this.$resetForm(this.addAvatarInfo)
      this.$log(row)
      this.addBox.showHide = true
      this.addAvatarInfo.id = row.id
      this.addAvatarInfo.useTime = row.useTime
      this.addAvatarInfo.receiveAmount = row.receiveAmount
      this.addAvatarInfo.receiveType = row.receiveType
      this.addAvatarInfo.remark = row.remark
      this.addAvatarInfo.iconName = row.iconName
      this.addAvatarInfo.iconUrl = row.iconUrl
      this.timeCotinue = [row.receiveStartTime === null ? '' : row.receiveStartTime, row.receiveEndTime ===
					null ? '' : row.receiveEndTime
      ]
    },

    // 添加|修改
    saveIconDataClick() {
      this.$log(this.addAvatarInfo)
      if (this.dialogStatus === 'create') {
        saveIconData(this.addAvatarInfo).then(res => {
          if (res.data.success) {
            this.$message.success('操作成功')
            this.getList()
          } else {
            this.$message.error(res.data.msg)
          }
          this.$resetForm(this.addAvatarInfo)
        })
      } else {
        updateIconData(this.addAvatarInfo).then(res => {
          if (res.data.success) {
            this.$message.success('操作成功')
            this.getList()
          } else {
            this.$message.error(res.data.msg)
          }
          this.$resetForm(this.addAvatarInfo)
        })
      }
      this.addBox.showHide = false
    },
    deleteAvatar(boxid) {
      this.$confirm('确定要删除该头像么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteIconData({
          'id': boxid
        }).then(res => {
          if (res.data.success) {
            this.$message.success('操作成功')
            this.getList()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {

      })
    },
    // 头像开关
    avatarOnlineState(event, scope) {
      const id = scope.row.id
      updateIconStatus({
        'id': id
      }).then(res => {
        if (res.data.success) {
          this.$message.success('操作成功')
          this.getList()
        } else {
          this.$message.error(res.data.msg)
          this.getList()
        }
      })
    },
    successUpload(data, flag) {
      this.addAvatarInfo.iconUrl = data
    }
  }
}
</script>
<style>
	.sortable-ghost {
		opacity: .8;
		color: #fff !important;
		background: #3b425d !important;
	}
</style>
<style lang="scss" scoped>
	$mainColor:#3b425d; // 主色调
	$disabledColor: #909399; //禁用色
	$hoverColor:#1D143C; // 鼠标停留主色调浅色

	::v-deep .el-select .el-input.is-focus .el-input__inner {
		border-color: $mainColor;
	}

	::v-deep .el-input__inner:focus {
		border-color: $mainColor;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.price-input {
		width: 70px;
	}

	.addBox-dialog {
		::v-deep .el-dialog__body {
			padding: 10px 80px;
		}

		::v-deep .image-slot {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 100%;
			height: 100%;
			background: #f5f7fa;
			color: #909399;
			font-size: 40px;
		}

		::v-deep .el-textarea__inner:focus {
			outline: 0;
			border-color: $mainColor;
		}
	}

	.upload-btn {
		font-size: 14px;
		color: #ffffff;
	}

	.editer {
		border-radius: 8px;
		float: left;
		box-sizing: border-box;
		color: #606266;

		::v-deep .ql-container {
			height: 440px;
			border-radius: 0px 0px 8px 8px;
		}

		::v-deep .ql-toolbar.ql-snow {
			border-radius: 8px 8px 0px 0px;
		}
	}

	.dialog-warningSetting {
		::v-deep.el-input {
			width: 110px;
		}

		.price-input {
			width: 100px;
		}

		.el-icon {

			&-circle-plus,
			&-remove {
				font-size: 22px;
				color: #3b425d;
				margin-left: 10px;

			}
		}

		ul {
			list-style-type: none;
			margin-top: 20px;
			padding: 0;

			li {
				margin: 0 0 30px 0px;
				display: flex;
				flex-direction: row;
				align-items: center;

				i {
					color: #D1D5DD;
				}
			}
		}

		.warning-title {
			font-size: 16px;
			color: #14162E;

			&-right {
				font-size: 16px;
				color: #14162E;
				margin-left: 80px;
			}

			&-right2 {
				font-size: 16px;
				color: #14162E;
				margin-left: 20px;
			}
		}
	}

	.table-btn {
		width: 90px;
		height: 35px;
		line-height: 35px;
		padding: 0;
		background: #e7ecf8;
		border: 1px solid $mainColor;
		border-radius: 8px;
		font-size: 14px;
		color: $mainColor;

		&:hover {
			background: $mainColor;
			color: #fff;
		}

		&:focus {
			background-color: #e7ecf8;
		}
	}

	.filter-container {
		width: 100%;
		height: 48px;
		line-height: 48px;
		margin-bottom: 30px;

		.filter-item {
			display: inline-block;
			vertical-align: middle;
			margin-bottom: 10px;
		}

		.top-btn {
			font-size: 14px;
			color: #ffffff;
		}

		.kInput {
			position: absolute;
			right: 20px;
		}
	}

	.chargeform {
		display: flex;
		flex-direction: row;
	}
</style>
